package com.yayohos.locationmanager.helper.continuoustask;


import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * 持续任务，用于定位调度
 *
 * @date 2021/5/26
 */
public class ContinuousTask extends EventHandler implements Runnable {
    private String taskId;
    private ContinuousTaskScheduler continuousTaskScheduler;
    private ContinuousTaskRunner continuousTaskRunner;


    public ContinuousTask(EventRunner runner, String tId, ContinuousTaskRunner cTaskRunner)
            throws IllegalArgumentException {
        super(runner);
        this.taskId = tId;
        this.continuousTaskScheduler = new ContinuousTaskScheduler(this);
        this.continuousTaskRunner = cTaskRunner;
    }

    /**
     * 延迟
     *
     * @param delay 延迟时长 ms
     */
    public void delayed(long delay) {
        continuousTaskScheduler.delayed(delay);
    }

    /**
     * pause
     */
    public void pause() {
        continuousTaskScheduler.onPause();
    }

    /**
     * resume
     */
    public void resume() {
        continuousTaskScheduler.onResume();
    }

    /**
     * stop
     */
    public void stop() {
        continuousTaskScheduler.onStop();
    }

    @Override
    public void run() {
        continuousTaskRunner.runScheduledTask(taskId);
    }

    void schedule(long delay) {
        postTask(this, delay);
    }

    /**
     * 任务注销
     */
    void unregister() {
        removeTask(this);
    }

    /**
     * 获取当前时间
     *
     * @return System.currentTimeMillis();
     */
    long getCurrentTime() {
        return System.currentTimeMillis();
    }

    /**
     * 任务回调接口
     */
    public interface ContinuousTaskRunner {
        /**
         * runScheduledTask
         *
         * @param taskId Callback to take action when scheduled time is arrived.
         *               Called with given taskId in order to distinguish which task should be run,
         *               in case of same {@linkplain ContinuousTaskRunner} passed to multiple Tasks
         */
        void runScheduledTask(String taskId);
    }
}
